package com.innovation.ic.im.end.data.listener;

import com.innovation.ic.b1b.framework.manager.ThreadPoolManager;
import com.innovation.ic.im.end.base.thread.data.ImportRedisDataThread;
import com.innovation.ic.im.end.base.value.config.ImportRedisDataScriptConfig;
import com.innovation.ic.im.end.base.value.config.ZookeeperParamConfig;
import com.innovation.ic.im.end.base.value.config.ZookeeperPathDataParamConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @desc   自动加载导入数据任务
 * @author linuo
 * @time   2023年4月24日15:05:54
 */
@Slf4j
@Component
public class StartHandlerListener implements ApplicationListener<ApplicationStartedEvent> {
    @Resource
    private ImportRedisDataScriptConfig importRedisDataScriptConfig;

    @Resource
    protected ZookeeperPathDataParamConfig zookeeperPathDataParamConfig;

    @Resource
    protected ZookeeperParamConfig zookeeperParamConfig;

    @Resource
    private ThreadPoolManager threadPoolManager;

    @Resource
    protected CuratorFramework curatorFramework;

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        try {
            InterProcessMutex lock = new InterProcessMutex(curatorFramework, zookeeperPathDataParamConfig.getInitImportRedisData());
            if (lock.acquire(zookeeperParamConfig.getInitImportRedisDataWaitingLockTime(), TimeUnit.MINUTES)) {
                String[] scripts = importRedisDataScriptConfig.getScripts();
                ImportRedisDataThread importRedisDataThread = new ImportRedisDataThread(scripts);
                threadPoolManager.execute(importRedisDataThread);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}